/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

import * as ts from 'typescript';

import * as path from './path';
import {createNotEmittedStatement, updateSourceFileNode} from './transformer_util';

/** Marks tsickle generated .d.ts's with a comment we can find later. */
export function makeTsickleDeclarationMarkerTransformerFactory(
    options: ts.CompilerOptions): ts.CustomTransformerFactory {
  return (context: ts.TransformationContext): ts.CustomTransformer => {
    return {
      transformBundle(): ts.Bundle {
        // The TS API wants declaration transfomers to be able to handle Bundle,
        // but we don't support them within tsickle.
        throw new Error('did not expect to transform a bundle');
      },
      transformSourceFile(sf: ts.SourceFile): ts.SourceFile {
        if (!options.rootDir) return sf;
        let syntheticFirstStatement = createNotEmittedStatement(sf);
        syntheticFirstStatement = ts.addSyntheticTrailingComment(
            syntheticFirstStatement, ts.SyntaxKind.SingleLineCommentTrivia,
            `!! generated by tsickle from ${
                path.relative(options.rootDir, sf.fileName)}`,
            /*hasTrailingNewLine=*/ true);
        return updateSourceFileNode(sf, ts.factory.createNodeArray([
          syntheticFirstStatement, ...sf.statements
        ]));
      }
    };
  };
}
